#include "prs_odbDatabase.h"

using namespace prs;

//**TRuleOdbDatabase**///////////////////////////////////////////////////////////
TRuleOdbDatabase::TRuleOdbDatabase( snt::text::TContext &Context
								  , snt::TRule &ROdbTable
								  , svl::TVariant &Parent
								  )
								  : parent(Parent)
								  , This(this)
								  {
	snt::TReturn          Return;
	snt::text::TEndOfText Eof(Context);
	snt::TFVoid			  F;
	
	//////////////////////////////////////
	//	 |<--------------|						  
	// ->|-> ROdbTable ->|-> Eof -> Return 
	
	this->Local(parent)
	| F.New(FDatabase, This) & A.New()
	;
	
	A
	| ROdbTable.New() & A.New()
	| /*Eof.New() &*/ Return.New()
	;
}

void TRuleOdbDatabase::FDatabase(snt::TParams &Params){
	TRuleOdbDatabase *This = dynamic_cast<TRuleOdbDatabase*>(Params.Pop().Pointer());
	TAttrNode *parent      = dynamic_cast<TAttrNode*>(This->parent.Pointer());

	TNodeOdbDatabase  *Node = new TNodeOdbDatabase;
	
	parent->OldChildren.Array.Add( Node, true );
	This->parent = Node;
}


//**TNodeOdbDatabase**///////////////////////////////////////////////////////////////////////
void TNodeOdbDatabase::odbSync( TOdbParams Params ){
	TNodeOdb* Child;
	Params.Path << Params.Root << ".";			
	
	odb::TFieldTable *root = Params.I.Connect.AllFields.SearchTableByPath( Params.Path );
	bool Exists;
	odb::TField *curF;
	
	Params.I.Connect.StartTransaction();
	
	for( int i = 0; i < root->Fields.Count(); i++ ){
		Exists = false;
		curF = &root->GetFields().Get(i);
		for( int j = 0; j < OldChildren.Array.Count(); j++ ){
			Child = dynamic_cast<TNodeOdb*>( &OldChildren.Array.Get(j) );
			if( Child ){
				if( Params.mName + Child->id.GetValue() == curF->Name ){
					Exists = true;
					break;
				}
			}
		}
		if( !Exists ){
			Params.D.Path( Params.Root ); 
			  Params.D.Table( curF->Name );
			Params.D.Execute();
		}
	}
	
	for( int i = 0; i < OldChildren.Array.Count(); i++ ){
		Child = dynamic_cast<TNodeOdb*>( &OldChildren.Array.Get(i) );
		if( Child ){
			Child->odbSync( Params );
		}
	}

	Params.I.Connect.Commit();
}